package org.jeecgframework.web.material.service.impl;

import java.util.Collections;
import java.util.List;

import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.web.material.entity.ProductProgressEntity;
import org.jeecgframework.web.material.service.ProductProgressServiceI;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("productProgressService")
@Transactional
public class ProductProgressServiceImpl extends CommonServiceImpl implements
		ProductProgressServiceI {

	public List queryMain(ProductProgressEntity po) {
		String hql = "select obj from ProductProgressEntity obj group by obj.typeId.id";
		return this.findByQueryString(hql);
	}
	
	public List queryProgress(ProductProgressEntity po) {
		ProductProgressEntity progress = this.getEntity(ProductProgressEntity.class, po.getId());
		if ("1".equals(progress.getFlag())) {
		    String hql = "select obj from ProductProgressEntity obj where obj.productId.id = '"+progress.getProductId().getId()+"'";
		    return this.findByQueryString(hql);
		}else if("2".equals(progress.getFlag())){
			String hql = "select obj from ProductProgressEntity obj where obj.typeId.id = '"+progress.getTypeId().getId()+"'";
		    return this.findByQueryString(hql);
		}
		return Collections.EMPTY_LIST;
	}
	
	@Override
	public void addMain(ProductProgressEntity po) {
		TSUser user = ResourceUtil.getSessionUserName();
		// 产品ID不为空 每一个产品ID对应一套生产过程
		if ("1".equals(po.getFlag())) {
			for (ProductProgressEntity obj : po.getProgressList()) {
				obj.setCompanyId(user.getCompany());
				obj.setProductId(po.getProductId());
				this.save(obj);
			}
		} else if ("2".equals(po.getFlag())) {// 每一类产品对应一套生产过程
			for (ProductProgressEntity obj : po.getProgressList()) {
				obj.setCompanyId(user.getCompany());
				obj.setTypeId(po.getTypeId());
				obj.setFlag("2");
				this.save(obj);
			}
		}

	}

	@Override
	public void deleteMain(ProductProgressEntity po) {
		// 产品ID不为空 每一个产品ID对应一套生产过程
		ProductProgressEntity progress = this.getEntity(ProductProgressEntity.class, po.getId());
		if ("1".equals(progress.getFlag())) {
			String sql = "delete from product_progress where product_id = '"+progress.getProductId().getId()+"'";
			super.executeSql(sql);
		}else if ("2".equals(progress.getFlag())) {// 每一类产品对应一套生产过程
			String sql = "delete from product_progress where type_id = '"+progress.getTypeId().getId()+"'";
			super.executeSql(sql);
		}
	}

	@Override
	public void updateMain(ProductProgressEntity po) {
		this.deleteMain(po);
		this.addMain(po);

	}

}